package com.bjpowernode.controller;

import com.bjpowernode.entity.Student;
import com.bjpowernode.service.StudentService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String id=request.getParameter("id");
            String name=request.getParameter("name");
            String email=request.getParameter("email");
            String age=request.getParameter("age");

         //创建spring的容器对象
        //String configure="spring.xml";
        // applicationContext=new ClassPathXmlApplicationContext(configure);
        //System.out.println("容器对象的信息"+applicationContext);

        WebApplicationContext webApplicationContext=null;
        //获取ServletContext中的容器对象
        String key="WebApplicationContext.ROOT_WEB_APPLICATION-CONTEXT-ATTRIBUTE";
        Object attr=getServletContext().getAttribute(key);
        if(attr!=null){
            webApplicationContext=(WebApplicationContext) attr;
        }

        //获取service对象
       StudentService service=(StudentService)webApplicationContext.getBean("studentService");

        Student student=new Student();
        Integer id1=Integer.valueOf(id);
        student.setId(id1);
        student.setName(name);
        student.setEmail(email);
        Integer age1=Integer.valueOf(age);
        student.setAge(age1);
        service.register(student);

    //完成操作后，使用请求转发
        request.getRequestDispatcher("/result.jsp").forward(request,response);

    }


}
